<template>
  <div>
    <el-dialog title="上传附件" :visible.sync="uploadDialog" destroy-on-close width="30vw" @close="handleClose">
      <el-upload
          ref="upload" drag action='#' name="attachment"
          :before-upload="function (file, fileList) { return beforeUpload(file, fileList )}"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg，且不超过500kb</div>
      </el-upload>
    </el-dialog>
  </div>

</template>

<script>
import {uploadAttachment} from "@/api/blog/attachment";

export default {
  name: "AttachmentUpload",
  data() {
    return {
      uploadDialog: false
    }
  },
  methods: {
    beforeUpload(file) {
      if (this.validate(file)) {
        const formData = new FormData()
        formData.append("file", file)
        uploadAttachment(formData).then(res => {
          this.$message.success(res.message)
          this.handleClose(res)
        })
      }
    },
    openDialog() {
      this.uploadDialog = true
    },
    //头像校验
    validate(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //关闭处理
    handleClose(msg) {
      if (msg === null) {
        msg = ""
      }
      this.$emit("handle", msg)
      this.uploadDialog = false
    }
  }
}
</script>

<style scoped>
.el-upload, .el-upload-dragger {
  width: 100%;
}
</style>
